package com.weikuang.fareast.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.trello.rxlifecycle2.android.ActivityEvent;
import com.weikuang.fareast.R;
import com.weikuang.fareast.adapter.CheckAdapter;
import com.weikuang.fareast.bean.CheckBean;
import com.weikuang.fareast.bean.CheckChangeEvent;
import com.weikuang.fareast.bean.CheckDetailBean;
import com.weikuang.fareast.bean.CheckListEvent;
import com.weikuang.fareast.bean.QueryNewBean;
import com.weikuang.fareast.bean.SimpleBean;
import com.weikuang.fareast.http.MainHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.adapter.BaseRecyclerAdapter;
import cn.dlc.commonlibrary.ui.dialog.SureDialog;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.utils.ToastUtil;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class CheckActivity extends BaseActivity {
    @BindView(R.id.mTitleBar)
    TitleBar mTitleBar;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    String order_id = "";
    CheckAdapter mCheckAdapter;
    List<CheckBean> datasList = new ArrayList<>();
    @BindView(R.id.order)
    TextView order;

    QueryNewBean.DataBean data;
    List<QueryNewBean.DataBean> dataBeanList;
    private  int position;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mTitleBar.leftExit(this);
        InitRecyclerView();
        dataBeanList = (List<QueryNewBean.DataBean>)getIntent().getSerializableExtra("data");
        position = getIntent().getIntExtra("position",0);
        data = dataBeanList.get(position);
        if (data != null){
            order.setText(data.orderno);
            order_id = data.id;
            checkDetail(data.id);
        }

    }


    private void InitRecyclerView() {
        mCheckAdapter = new CheckAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mCheckAdapter);

        mCheckAdapter.setCallback(new CheckAdapter.VerifySelectback() {
            @Override
            public void onCheckClick(int position, boolean status, BaseRecyclerAdapter.CommonHolder commonHolder) {
                if (status) {
                    mCheckAdapter.getData().get(position).check = false;
                }else {
                    mCheckAdapter.getData().get(position).check = true;
                }
                mCheckAdapter.notifyDataSetChanged();
            }
        });

    }


    @OnClick({ R.id.btn_read,R.id.btn_abandon,R.id.btn_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_read:
                SureDialog dialog = new SureDialog(getActivity(),"请确认是否提交审核");
                dialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        checkCommit();
                    }

                    @Override
                    public void cancle() {

                    }
                });

                break;
            case R.id.btn_abandon:
                SureDialog dialog1 = new SureDialog(getActivity(),"请确认是否订单废弃");
                dialog1.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        checkKill(order_id);
                    }

                    @Override
                    public void cancle() {

                    }
                });

                break;
            case R.id.btn_change:
                Intent mIntent = new Intent(CheckActivity.this,ChangeDataActivity.class);
                mIntent.putExtra("data",data);
                startActivity(mIntent);
                finishActivity();
                break;
        }
    }

    private void checkKill(String orderId) {
        showWaitingDialog("请等待", true);
        MainHttp.get().checkKill(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        dismissWaitingDialog();
                        finishActivity();
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                        dismissWaitingDialog();
                    }
                });
    }




    private void checkDetail(String orderId) {
        MainHttp.get().checkDetail(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<CheckDetailBean>() {
                    @Override
                    public void onSuccess(CheckDetailBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        datasList.clear();
                        for (int i = 0; i < hotelBean.data.size(); i++) {
                            CheckBean bean1 = new CheckBean(hotelBean.data.get(i).hotel, hotelBean.data.get(i).office, hotelBean.data.get(i).title,
                                    hotelBean.data.get(i).goods_id, Integer.valueOf(hotelBean.data.get(i).amount), Integer.valueOf(hotelBean.data.get(i).bad)
                                    ,Integer.valueOf(hotelBean.data.get(i).back),String.valueOf(hotelBean.data.get(i).ctime), hotelBean.data.get(i).amount,false,Integer.parseInt(data.status));
                            datasList.add(bean1);
                        }
                        mCheckAdapter.setNewData(datasList);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void checkCommit() {
        String goods_id = "", nums = "", bads = "",backs = "";
        clearNums();
        if (datasList!= null && datasList.size()==0){
            ToastUtil.show(CheckActivity.this, "数据为空");
            return;
        }
        for (int i = 0; i < datasList.size(); i++) {
            goods_id = goods_id + datasList.get(i).id + ",";
        }
        if (!TextUtils.isEmpty(goods_id)) {
            goods_id = goods_id.substring(0, goods_id.length() - 1);
        } else {
            goods_id = "";
        }

        for (int i = 0; i < datasList.size(); i++) {
            nums = nums + datasList.get(i).nums + ",";
            bads = bads + datasList.get(i).num_loss + ",";
            backs = backs + datasList.get(i).backs + ",";
        }
        if (!TextUtils.isEmpty(nums)) {
            nums = nums.substring(0, nums.length() - 1);
        } else {
            nums = "";
        }
        if (!TextUtils.isEmpty(bads)) {
            bads = bads.substring(0, bads.length() - 1);
            backs = backs.substring(0, backs.length() - 1);
        } else {
            bads = "";
            backs = "";
        }
        showWaitingDialog("请等待", true);
        MainHttp.get().checkCommit(order_id, goods_id, nums, bads,backs)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean bean) {
                        ToastUtil.show(CheckActivity.this, bean.msg);
                        dismissWaitingDialog();
                        datasList.clear();
                        mCheckAdapter.setNewData(datasList);
                        position ++;
                        if (dataBeanList.size() > position) {
                            data = dataBeanList.get(position);
                            if (data != null) {
                                order.setText(data.orderno);
                                order_id = data.id;
                                checkDetail(data.id);
                            }
                        }else {
                            ToastUtil.show(CheckActivity.this, "已经审核到最后一个了");
                        }
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(CheckActivity.this, message);
                        dismissWaitingDialog();
                    }
                });
    }

    /**
     * 是否清空为0数据
     * @return
     */
    private void clearNums(){
        Iterator<CheckBean> ite = datasList.iterator();
        while(ite.hasNext()){
            CheckBean str = (CheckBean)ite.next();
            if(str.nums == 0 && str.backs == 0&&str.num_loss==0){
                ite.remove();
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CheckChangeEvent event) {
        if (data != null){
            order.setText(data.orderno);
            order_id = data.id;
            checkDetail(data.id);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new CheckListEvent());
        EventBus.getDefault().unregister(this);
    }
}
